<template>
  <div class="order-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索记录ID/图书编号/保养类型"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增记录
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredRecords" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="recordId" label="记录ID" width="180" sortable align="center" />
      <el-table-column prop="bookId" label="图书编号" width="150">
        <template #default="{ row }">
          <el-tag effect="plain" type="info">
            {{ row.bookId }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="maintainType" label="保养类型" width="140">
        <template #default="{ row }">
          <el-tag effect="plain" :type="typeTagType[row.maintainType]">
            {{ row.maintainType }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="处理状态" width="140" align="center">
        <template #default="{ row }">
          <el-tag :type="statusTagType[row.status]" effect="light">
            {{ statusOptions.find(s => s.value === row.status)?.label }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="maintainDate" label="保养日期" width="140" sortable />
      <el-table-column prop="responsible" label="负责人" width="150" />
      <el-table-column prop="cost" label="费用" width="120" align="center">
        <template #default="{ row }">
          <span style="color: #2ecc71;">¥{{ row.cost.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="note" label="处理措施" width="160">
        <template #default="{ row }">
          <div class="note-preview">{{ row.note }}</div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.recordId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑保养记录' : '新增保养记录'"
      width="680"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="记录ID" prop="recordId">
          <el-input 
            v-model="formData.recordId" 
            :disabled="isEditMode"
            placeholder="MA开头+8位日期+3位序列"
          />
        </el-form-item>
        <el-form-item label="图书编号" prop="bookId">
          <el-input 
            v-model="formData.bookId"
            placeholder="请输入图书编号（如：BK2024001）"
          />
        </el-form-item>
        <el-form-item label="保养类型" prop="maintainType">
          <el-select 
            v-model="formData.maintainType"
            placeholder="请选择类型"
            style="width: 100%"
          >
            <el-option
              v-for="item in maintainTypes"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select 
            v-model="formData.status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="保养日期" prop="maintainDate">
          <el-date-picker
            v-model="formData.maintainDate"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="负责人" prop="responsible">
          <el-input 
            v-model="formData.responsible"
            placeholder="请输入负责人姓名"
          />
        </el-form-item>
        <el-form-item label="费用" prop="cost">
          <el-input-number
            v-model="formData.cost"
            :min="0"
            :precision="2"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="处理措施" prop="note">
          <el-input 
            type="textarea"
            v-model="formData.note" 
            rows="3"
            placeholder="请输入具体处理措施"
            show-word-limit
            maxlength="100"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 保养类型配置
const maintainTypes = [
  '除尘消毒',
  '封面修复',
  '书页粘合',
  '装订加固',
  '防虫处理',
  '数字化备份'
]

// 处理状态选项
const statusOptions = [
  { value: 'pending', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' }
]

// 标签样式映射
const typeTagType = {
  '除尘消毒': 'info',
  '封面修复': 'warning',
  '书页粘合': 'danger',
  '装订加固': 'success',
  '防虫处理': 'primary',
  '数字化备份': ''
}

const statusTagType = {
  'pending': 'warning',
  'processing': 'primary',
  'completed': 'success'
}

// 初始数据（10条）
const records = ref([
  {
    recordId: 'MA20240520001',
    bookId: 'BK2024001',
    maintainType: '封面修复',
    status: 'completed',
    maintainDate: '2024-05-20',
    responsible: '王修复师',
    cost: 150.00,
    note: '更换皮质封面，使用pH中性胶水'
  },
  {
    recordId: 'MA20240520002',
    bookId: 'BK2024003',
    maintainType: '书页粘合',
    status: 'processing',
    maintainDate: '2024-05-19',
    responsible: '李维护员',
    cost: 80.50,
    note: '修复第12-15页脱页问题'
  },
  {
    recordId: 'MA20240520003',
    bookId: 'BK2024005',
    maintainType: '防虫处理',
    status: 'pending',
    maintainDate: '2024-05-18',
    responsible: '张养护员',
    cost: 200.00,
    note: '全本无酸纸包裹防虫处理'
  },
  {
    recordId: 'MA20240520004',
    bookId: 'BK2024007',
    maintainType: '装订加固',
    status: 'completed',
    maintainDate: '2024-05-17',
    responsible: '赵师傅',
    cost: 120.00,
    note: '重装锁线，更换书脊布料'
  },
  {
    recordId: 'MA20240520005',
    bookId: 'BK2024009',
    maintainType: '数字化备份',
    status: 'processing',
    maintainDate: '2024-05-16',
    responsible: '数字部',
    cost: 500.00,
    note: '600dpi高清扫描存档'
  },
  {
    recordId: 'MA20240520006',
    bookId: 'BK2024002',
    maintainType: '除尘消毒',
    status: 'completed',
    maintainDate: '2024-05-15',
    responsible: '清洁组',
    cost: 60.00,
    note: '全书除尘+紫外线消毒处理'
  },
  {
    recordId: 'MA20240520007',
    bookId: 'BK2024004',
    maintainType: '书页粘合',
    status: 'pending',
    maintainDate: '2024-05-14',
    responsible: '李维护员',
    cost: 90.00,
    note: '修复第78页撕裂处'
  },
  {
    recordId: 'MA20240520008',
    bookId: 'BK2024006',
    maintainType: '防虫处理',
    status: 'completed',
    maintainDate: '2024-05-13',
    responsible: '张养护员',
    cost: 180.00,
    note: '樟木盒保存处理'
  },
  {
    recordId: 'MA20240520009',
    bookId: 'BK2024008',
    maintainType: '装订加固',
    status: 'processing',
    maintainDate: '2024-05-12',
    responsible: '赵师傅',
    cost: 135.00,
    note: '加固书角，更换环衬页'
  },
  {
    recordId: 'MA20240520010',
    bookId: 'BK2024010',
    maintainType: '数字化备份',
    status: 'pending',
    maintainDate: '2024-05-11',
    responsible: '数字部',
    cost: 450.00,
    note: 'OCR文字识别校对'
  }
])

// 搜索功能
const searchText = ref('')
const filteredRecords = computed(() => {
  return records.value.filter(record => {
    return Object.values(record).some(value => 
      String(value).toLowerCase().includes(searchText.value.toLowerCase())
  )})
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
  recordId: '',
  bookId: '',
  maintainType: '除尘消毒',
  status: 'pending',
  maintainDate: new Date().toISOString().split('T')[0],
  responsible: '',
  cost: 0,
  note: ''
})

// 表单验证规则
const formRules = {
  recordId: [
    { required: true, message: '请输入记录ID', trigger: 'blur' },
    { pattern: /^MA\d{8}\d{3}$/, message: '格式要求：MA+8位日期+3位序列', trigger: 'blur' }
  ],
  bookId: [
    { required: true, message: '请输入图书编号', trigger: 'blur' },
    { pattern: /^BK\d{7}$/, message: '格式要求：BK+7位数字', trigger: 'blur' }
  ],
  maintainType: { required: true, message: '请选择保养类型', trigger: 'change' },
  responsible: [
    { required: true, message: '请输入负责人', trigger: 'blur' },
    { min: 2, max: 20, message: '长度2-20个字符', trigger: 'blur' }
  ],
  cost: [
    { required: true, message: '请输入费用', trigger: 'blur' },
    { type: 'number', min: 0, max: 9999, message: '金额范围0-9999元', trigger: 'blur' }
  ]
}

// 操作函数
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

const handleDelete = (recordId) => {
  ElMessageBox.confirm('确定删除该保养记录？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    records.value = records.value.filter(u => u.recordId !== recordId)
    ElMessage.success('删除成功')
  })
}

const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = records.value.findIndex(u => u.recordId === formData.recordId)
    records.value.splice(index, 1, { ...formData })
  } else {
    if (records.value.some(u => u.recordId === formData.recordId)) {
      return ElMessage.warning('记录ID已存在')
    }
    records.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '修改成功' : '新增成功')
}

const resetForm = () => {
  formData.recordId = ''
  formData.bookId = ''
  formData.maintainType = '除尘消毒'
  formData.status = 'pending'
  formData.maintainDate = new Date().toISOString().split('T')[0]
  formData.responsible = ''
  formData.cost = 0
  formData.note = ''
}
</script>

<style scoped lang="scss">
.order-management {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(44, 62, 80, 0.08);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  :deep(.table-header) th {
    background-color: #f8fafc !important;
    color: #64748b;
    font-weight: 600;
    height: 56px;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(44, 62, 80, 0.08);
    
    .el-tag {
      font-size: 13px;
      padding: 0 8px;
      height: 26px;
      line-height: 24px;
    }
  }

  .note-preview {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height: 1.5;
    color: #4a5568;
  }
}

.el-dialog {
  border-radius: 12px;
  
  .el-dialog__header {
    border-bottom: 1px solid #e2e8f0;
    margin: 0 24px;
    padding: 24px 0 16px;
  }
  
  .el-dialog__body {
    padding: 24px 32px;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #e2e8f0;
    padding: 16px 24px;
  }
}

.el-form-item {
  margin-bottom: 20px;
}
</style>